/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text,
    Spinner,
    useTheme,
    List,
    Button,
    ListItem,
    Skeleton,
    Embed,
    MenuList,
    MenuItem,
    IconPackage,
    MenuDivider,
    IconButton, IconMoreVertical, useToast, IconRefButton, VerticalMenu, DdMenuItem
} from "customize-easy-ui-component";
import {useFragment} from "react-relay";
import {useFirebaseImage} from "../../comp/Image";
import {FadeImage} from "../../comp/FadeImage";

//import { useDeleteReport, useLookReports } from "./db";
//import { useFirebaseImage } from "../../Image";
//import { Link as RouterLink,useLocation, useRoute } from "wouter";
//import { FadeImage } from "../../FadeImage";
import { Link as RouterLink } from "../../routing/Link";
import {useContext} from "react";
import RoutingContext from "../../routing/RoutingContext";
import {BoundReports$key} from "./__generated__/BoundReports.graphql";
import useAbandonDetailMutation from "../useAbandonDetailMutation";
import useDeleteReportMutation from "./useDeleteReportMutation";
import useFlowReportMutation from "../useFlowReportMutation";
import {ModelTypeArr} from "../../report/modelConfigs";
const graphql = require("babel-plugin-relay/macro");


interface BoundReportsProps {
  id: string;
    isp: BoundReports$key;
}
//某个检验ISP 底下的报告队列。
export const BoundReports: React.FunctionComponent<
  BoundReportsProps
> = props => {
  const theme = useTheme();
  console.log("看BoundReports filter =ispId=", props.id );


  const [filter, setFilter] = React.useState({ id:props.id });
  //const {loading, error, items, loadMore } =useLookReports(filter);
    const data = useFragment(
        graphql`
            fragment BoundReports on Isp {
                id,bus{id}
                report {id, stm{id,sta,due}, type,path, isp{id,no} }
                reps  {
                    edges {
                        node {
                         id,type, path, stm{id,sta,due}
                        }
                    }
                }
            }
        `,
        props.isp
    );
    const { reps:list, report:mainrep }=data;
    const parentId= data?.id;
    const items = list && list.edges ? list.edges.map(edge => edge?.node) : [];

  console.log("所有挂接的报告 filter=", filter, items);
  //就算id切换了，本组件的数据还是会被appollo自动缓存的，id变化不会一定导致重新查询后端数据库的，看着像页面显示的缓存。
  //根据id和界面操作后的参数，来要修正graphQL的Query()的参数 = 要做重新查询。
  React.useEffect(() => {
    setFilter({ id:props.id });
  }, [props.id,]);
  //滚动条触发的更多查询。初始查询的记录满员必须大于让滚动条开启{满屏了}的数量，否则无法触发后续更多查询。
  const ref = React.useRef();
  /*  const [hasMore, setHasMore] = React.useState(true);
  const [fetching] = useInfiniteScroll({
    container: ref as any,
    hasMore: hasMore,
    onFetch: () => toLoadMore()
   });
  async function toLoadMore() {
    loadMore({
      variables: {
        offset: items.length,
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        console.log("fetchMoreResult来看="+ JSON.stringify(fetchMoreResult)+",原来="+ JSON.stringify(prev) );
        if (!fetchMoreResult)   return prev;
        if (!fetchMoreResult.recipe)   return prev;
        if(fetchMoreResult.recipe.length===0)
          setHasMore(false);
        if(prev.recipe.length + fetchMoreResult.recipe.length > 2000 )
          setHasMore(false);
        return Object.assign({}, prev, {
          recipe: [...prev.recipe, ...fetchMoreResult.recipe],
        });
      },
    })
  } */


  return (
        <div css={{overflowY: "auto", height: "100%",}}
        >
          { !items && (
            <Text
              muted
              css={{
                display: "block",
                fontSize: theme.fontSizes[0],
                margin: theme.spaces.lg
              }}
            >
              This user currently 没有东西.
            </Text>
          )}

          <List>
            {items && items.map(report => (
                <ReportListItem
                    id={report?.id}
                    key={report?.id!}
                    editable
                    report={report as any}
                    parentId={parentId}
                    mainrep={mainrep}
                />
            ))}
          </List>

          {(!items || items.length===0) && (
            <div css={{ textAlign: "center" }}>
              <Button  onPress={ () => void 0 } >
                检验ID　{props.id}　底下还没有现成的报告可看
              </Button>
            </div>
          )}
         <div css={{paddingTop:'3rem', textAlign: "center" }}>
          已拉到最后
         </div>
       </div>
  );
};

//缩略图和完整图都是同一个图片的数据内容，　不做差异化处理！
export function ReportListItem({ report, id, highlight ,parentId, mainrep }: any) {
  const theme = useTheme();
  const toast = useToast();
    const {history } = useContext(RoutingContext);
  const {  error } = useFirebaseImage("thumb-sm@", report.image);
  //Todo: 根据身份识别场景，　区分按钮点击的url，或是隐藏按钮。
  //报告编制人的报告入口链接
  const href = `/inspect/${parentId}/report/${id}`;
  //Todo: 类型和版本；　report/EL-DJ/ver/1/preview/

//TODO:新路由当前激活的  const [isActive,] = useRoute(href);
    const isActive=false;
  //const [, setLocation] = useLocation();
  //const [repId, setRepId] = React.useState(null);
    const {call:handleDelete,doing:abandoning, called:abandoned, reset:abandonrest}= useDeleteReportMutation();
    //另外一个流转命令在IspDetail.tsx页面
    const {call:flowReportFunc,doing:flowing, called:flowed, reset:flowreset}= useFlowReportMutation();

/*  const { submit:updateFunc, } = useDeleteReport({
    repId, reason:'测试期直接删'
  });
  //下面highlight. 是algoliasearch.Response返回的，必须有预先定义。
  async function handleDelete(id: string) {
    try {
      await updateFunc();
    } catch (err: any) {
      toast({
        title: "后端报错",
        subtitle: err.message,
        intent: "error"
      });
      console.log("handleDelete返回", err);
      return;
    }
    setLocation("/inspect/"+ispId,  { replace: true } );
  }*/

//<ListItem 外面再套<RouterLink 若列表项还有可点击按钮的：在触摸屏可以正常，可电脑上不正常会优先触发<RouterLink
//【无法再用】<RouterLink href={href}> <ListItem整个点链接；因为DdMenu依赖于mount状态导致刷新后失效。
  return (
      <ListItem
              wrap={false}
              aria-current={isActive}
              onPress={(e) => {
                  //e?.preventDefault(); 不能添加！
                  e?.stopPropagation();
                  history.push(href);
              }}
              css={{
                alignItems: "center",
                display: "flex",
                justifyContent: "space-between",
                "& em": {
                  fontStyle: "normal",
                  color: theme.colors.text.selected
                },
                backgroundColor: isActive ? theme.colors.background.tint1 : undefined,
                "& > *": {
                  flex: 1,
                  overflow: "hidden"
                }
              }}
              primary={ModelTypeArr[report.modeltype as keyof typeof ModelTypeArr]?.name +' '+ report.type}
              secondary={
                  (mainrep?.id===id ? (
                      `主报告号`
                  ) : (
                      `分项报告`
                  ) )
                  + ' ' + mainrep?.isp.no
              }
              contentAfter={
                  <VerticalMenu>
                      <DdMenuItem label="结束编制提交流转签字" onClick={(e) => {
                          flowReportFunc( id, href, "统一",3);
                          toast({title: "进入流程服务签名环节"});
                      }}>
                      </DdMenuItem>
                      <DdMenuItem label={`删除该${report.id}报告`} onClick={(e) => {
                          //后面参数parentId仅在前端使用，不是发给后端的。
                          handleDelete(report.id,'测试期直接删', parentId)
                      }}>
                      </DdMenuItem>
                  </VerticalMenu>
              }
    >
      { `编制日期 ${report.upLoadDate||''}` }
    </ListItem>
  );
}




//引入useInfiniteScroll使用的四个要素：有滚动条的组件innerRef，hasMore，onFetch()，fetching；
//<ScrollView >要么height:"100%"要么删除height参数让内容去撑开，不能使用height:"70%"之类的数，内部2次DIV嵌套,导致0.7*0.7=实际上内部高度。
//较上层DIV若是style={{ height: "xxx%" }}，注意若父辈元素都没限定最小的高度，那么就会导致由底下的内容撑开了，这等价于没height参数=实际无效！；"100%"若父辈有px数就听父辈的。
//<ListItem>组件，其中primary要用在填充较长的内容，contentAfter是相对简短的内容显示，不要颠倒；primary会截短，而contentAfter不会缩短。
/*
{
        report.sssdf && !error ? (
            <Embed css={{ width: "60px" }} width={75} height={50}>
                <FadeImage src={report.path} hidden />
            </Embed>
        ) : (
           report.modeltype
        )
        }
        <MenuItem contentBefore={<IconPackage />}
              onPress={async () => {
                  flowReportFunc( id, href, "统一",3);
                  await toast({title: "进入流程服务签名环节1"});
                        //history.push("/");
              } }
          >
        </MenuItem>
* */
